import { useDeepCompareEffect } from 'ahooks';
import { Input, message } from 'antd';
import React, { useState } from 'react';

const PATH_RE = /^\$(\['.+'\])*$/;
const MATCH_RE = /'.+?'/g;

export function renderPath(value) {
  // eslint-disable-next-line prefer-template
  return Array.isArray(value) ? '$' + value.map(part => `['${part}']`).join('') : '';
}

function PathInput({ value, onChange, ...rest }) {
  const [inputValue, setInputValue] = useState(renderPath(value));

  const handleInputValueBlur = e => {
    const { value: inputValue } = e.target;
    if (inputValue === '') {
      return;
    }
    if (!PATH_RE.test(inputValue)) {
      message.error("路径不满足$['xxx']['yyy']格式");
      setInputValue(renderPath(value));
      return;
    }
    const matches = inputValue.match(MATCH_RE);
    if (matches === null) {
      onChange([]);
    } else {
      const parts = matches.map(m => m.substring(1, m.length - 1));
      onChange(parts);
    }
  };

  useDeepCompareEffect(() => {
    setInputValue(renderPath(value));
  }, [value]);

  return (
    <Input
      onBlur={handleInputValueBlur}
      value={inputValue}
      onChange={e => setInputValue(e.target.value)}
      placeholder="输入路径，如：$['root']['request']['orderId']"
      {...rest}
    />
  );
}

export default PathInput;
